package com.lmf.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.servlet.http.HttpServletRequest;


public class TokenFilter extends ZuulFilter {
    private final Logger logger= LoggerFactory.getLogger(TokenFilter.class);
    //可以在请求被路由之前调用
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        //filter执行顺序，通过数字指定 优先级为0 值越大,优先级越低
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //是否执行该过滤器,此处为true，说明需要过滤 默认为false
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        logger.info("--->>> TokenFilter {},{}",request.getMethod(),request.getRequestURI().toString());
        String token=request.getParameter("token");
        //String token=request.getHeader("token");
        if(StringUtils.isNotBlank(token)){
            ctx.setSendZuulResponse(true);   //对请求进行路由
            ctx.setResponseStatusCode(200);
            ctx.set("isSussess",true);
            System.out.println("哈哈我已经走到这一步了");
            return null;
        }else{
            ctx.setSendZuulResponse(false);//阻止请求进行路由
            ctx.setResponseStatusCode(302);
            ctx.setResponseBody("token is empty");
            ctx.set("isSussess",false);
            return null;
        }

    }
}
